import { defineStore } from 'pinia'
import axios from 'axios'
import router from '../router'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    loading: false,
    error: null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.user,
    userRole: (state) => state.user ? state.user.role : null
  },
  
  actions: {
    async login(credentials) {
      this.loading = true
      this.error = null
      
      try {
        // Determine the correct endpoint based on role
        let endpoint = '';
        let userModel = {};
        
        if (credentials.role === 'admin') {
          endpoint = '/adminLogin';
          const response = await axios.post(endpoint, {
            aId: credentials.id,
            aPassword: credentials.password
          });
          
          if (response.data) {
            userModel = {
              id: response.data.aId,
              name: response.data.aName,
              role: 'admin'
            };
          }
        } else if (credentials.role === 'doctor') {
          endpoint = '/doctorLogin';
          const response = await axios.post(endpoint, {
            dId: credentials.id,
            dPassword: credentials.password
          });
          
          if (response.data) {
            userModel = {
              id: response.data.dId,
              name: response.data.dName,
              role: 'doctor'
            };
          }
        } else if (credentials.role === 'patient') {
          endpoint = '/patientLogin';
          const response = await axios.post(endpoint, {
            pId: credentials.id,
            pPassword: credentials.password
          });
          
          if (response.data) {
            userModel = {
              id: response.data.pId,
              name: response.data.pName,
              role: 'patient'
            };
          }
        }
        
        // Set user in store and localStorage
        this.user = userModel;
        localStorage.setItem('user', JSON.stringify(userModel));
        
        // Redirect based on role
        router.push(`/${credentials.role}`);
      } catch (error) {
        this.error = error.response?.data?.message || 'Login failed';
        console.error('Login error:', error);
      } finally {
        this.loading = false;
      }
    },
    
    async register(userData) {
      this.loading = true
      this.error = null
      
      try {
        let endpoint = '';
        
        if (userData.role === 'admin') {
          endpoint = '/insertAdminUser';
          await axios.post(endpoint, {
            aId: userData.id,
            aPassword: userData.password,
            aName: userData.name,
            aGender: userData.gender,
            aPhone: userData.phone,
            aCard: userData.card,
            aEmail: userData.email
          });
        } else if (userData.role === 'doctor') {
          endpoint = '/insertDoctorUser';
          await axios.post(endpoint, {
            dId: userData.id,
            dPassword: userData.password,
            dName: userData.name,
            dGender: userData.gender,
            dPhone: userData.phone,
            dCard: userData.card,
            dEmail: userData.email,
            dPost: userData.post,
            dIntroduction: userData.introduction,
            dSection: userData.section,
            dState: 1,
            dPrice: userData.price,
            dPeople: 0,
            dStar: 0,
            dAvgStar: 0
          });
        } else if (userData.role === 'patient') {
          endpoint = '/insertPatientUser';
          await axios.post(endpoint, {
            pId: userData.id,
            pPassword: userData.password,
            pName: userData.name,
            pGender: userData.gender,
            pPhone: userData.phone,
            pCard: userData.card,
            pEmail: userData.email,
            pState: 1,
            pBirthday: userData.birthday,
            pAge: userData.age
          });
        }
        
        // Redirect to login after successful registration
        router.push('/login');
      } catch (error) {
        this.error = error.response?.data?.message || 'Registration failed';
        console.error('Registration error:', error);
      } finally {
        this.loading = false;
      }
    },
    
    async recoverPassword(userData) {
      this.loading = true
      this.error = null
      
      try {
        let endpoint = '';
        
        if (userData.role === 'admin') {
          endpoint = '/resetAdminPassword';
          await axios.post(endpoint, {
            aId: userData.id,
            aEmail: userData.email,
            aPassword: userData.newPassword
          });
        } else if (userData.role === 'doctor') {
          endpoint = '/resetDoctorPassword';
          await axios.post(endpoint, {
            dId: userData.id,
            dEmail: userData.email,
            dPassword: userData.newPassword
          });
        } else if (userData.role === 'patient') {
          endpoint = '/resetPatientPassword';
          await axios.post(endpoint, {
            pId: userData.id,
            pEmail: userData.email,
            pPassword: userData.newPassword
          });
        }
        
        // Redirect to login after successful password reset
        router.push('/login');
      } catch (error) {
        this.error = error.response?.data?.message || 'Password recovery failed';
        console.error('Password recovery error:', error);
      } finally {
        this.loading = false;
      }
    },
    
    logout() {
      this.user = null;
      localStorage.removeItem('user');
      router.push('/login');
    }
  }
}); 